// index.js
const app = getApp();

Page({
  data: {
    // 独立柜子状态
    cabinet1: { status: 'A' },
    cabinet2: { status: 'B' },
    cabinet3: { status: 'A' },
    cabinet4: { status: 'B' },

    ID:'',
    status:'',

    currentFocus: 0,
    showPasswordInput: false,
    isProcessing: false,
    connectButtonText: '连接服务器',
  },

    onLoad() {
    // 注册页面到全局监听系统
    getApp().registerPage(this);
    
    // 初始化时同步全局数据
    this.syncGlobalData();
    this.updateCabinetStatus();
  },

  onUnload() {
    // 页面卸载时移除监听
    getApp().unregisterPage(this);
  },

  onShow() {
    // 隐藏微信原生tabBar
    wx.hideTabBar();
    this.loadCurrentState();
    app.initUserRole(app.globalData.userRoles.pass)
  },

  // 同步全局数据
  syncGlobalData() {
    const globalData = getApp().globalData;
    this.setData({
      ID: globalData.id,
      status: globalData.status
    });
  },

  // 响应全局数据更新（由app.js触发）
  updateData(payload) {
    this.setData({
      ID: payload.id,
      status: payload.status
    }, () => {
      this.updateCabinetStatus();
    });
  },
  //更新柜门状态
updateCabinetStatus() {
  const { ID, status } = this.data;
  console.log('[UPDATE] 原始输入:', ID, status);
  // 转换柜号
  const cabinetId = parseInt(ID, 10);
  if (isNaN(cabinetId) || cabinetId < 1 || cabinetId > 4) {
    console.error('无效柜号:', ID);
    return;
  }
  // 验证状态
  const validStatus = ['A', 'B'];
  if (!validStatus.includes(status)) {
    console.error('无效状态:', status);
    return;
  }

  // 执行更新
  this.setData({
    [`cabinet${cabinetId}.status`]: status
  }, () => {
    console.log('[SUCCESS] 更新后的柜状态:', this.data[`cabinet${cabinetId}`]);
  });
},
  // 保存状态到本地存储
  saveCurrentState() {
    wx.setStorageSync('indexState', {
      password: this.data.password,
      doorStatus: this.data.doorStatus,
      heaterStatus: this.data.heaterStatus,
      currentPassword: this.data.currentPassword
    });
  },
  //
  loadCurrentState() {
    const state = app.getCurrentState();
    this.setData({
      heaterStatus: state.isHeated,
      doorStatus: state.isDoorOpened,
      currentPassword: state.newPassword
    });
  },
checkProcessing() {
  if (this.data.isProcessing) {
    wx.showToast({ title: '请等待当前操作完成', icon: 'none' });
    return true;
  }
  this.setData({ isProcessing: true });
  return false;
},

  toggleDoor() {
    if (this.checkProcessing()) return;
    const success = app.sendCommand({ door: "33" });
    if (success) {
      wx.showToast({ title: '正在开门...', icon: 'loading' });
      app.updateDeviceState({ 
        isDoorOpened:true,
      });
    }
    setTimeout(() => this.setData({ isProcessing: false }), 5000);
  },

  // 新增提示函数
  showLockedAlert() {
    wx.showModal({
      title: '提示',
      content: '该柜格已满，无法开启',
      showCancel: false
    });
  },
  showAlert() {
    wx.showModal({
      title: '提示',
      content: '该柜格故障，无法开启',
      showCancel: false
    });
  },
    gotonext()
    {
      wx.navigateTo({
        url: '/pages/admindex/index'
      }) 
    }


});